package com.hrb.douban.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.TextView;

import com.hrb.commonsdk.okhttp.listener.DisposeDataListener;
import com.hrb.commonsdk.okhttp.request.RequestParams;
import com.hrb.douban.CustomApplication;
import com.hrb.douban.OnItemClickListener;
import com.hrb.douban.R;
import com.hrb.douban.activtity.FilmDetailsActivity;
import com.hrb.douban.activtity.SearchPageActivity;
import com.hrb.douban.adapter.ComingAdapter;
import com.hrb.douban.constant.ConstantCode;
import com.hrb.douban.constant.HttpConstants;
import com.hrb.douban.mview.GlideImageLoader;
import com.hrb.douban.mview.LoadingView;
import com.hrb.douban.network.RequestCenter;
import com.hrb.douban.record.Comingrecord;
import com.hrb.douban.record.SubjectsBean;
import com.hrb.douban.utils.ACache;
import com.hrb.douban.utils.ToastUtil;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.footer.ClassicsFooter;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.youth.banner.Banner;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;

/**
 * A simple {@link Fragment} subclass.
 */
public class PopularFragment extends Fragment {

    /*@BindView(R.id.banner)
    Banner banner;*/
    @BindView(R.id.list_view)
    RecyclerView recyclerView;
    @BindView(R.id.swipe_refresh)
    SmartRefreshLayout swipeRefresh;
    @BindView(R.id.popular_search)
    TextView popularSearch;
    @BindView(R.id.loading_view)
    LoadingView loadingView;
    private Unbinder unbinder;
    private int scrollY = 0;
    private ComingAdapter adapter;
    private int start = 0;
    private int lastPosition = 0;
    private int lastOffset = 0;
    private ACache cacheUtil;
    private static final String STROE="stroe";
    private static final String INTERNET="INTERNET";

    //https://www.jianshu.com/p/258d0dca4791 https://www.jianshu.com/p/991062d964cf https://blog.csdn.net/wangwangli6/article/details/70210808
    public PopularFragment() {
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        cacheUtil = ACache.get(CustomApplication.getContext());
        RequestParams params = new RequestParams();
        params.put("city", "哈尔滨");
        params.put("start", start + "");
        params.put("count", "20");
        requestData(params);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_popular, container, false);
        unbinder = ButterKnife.bind(this, view);
        GridLayoutManager gridLayoutManager = new GridLayoutManager(getContext(), 2);
        recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(@NonNull RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
            }

            @Override
            public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                //Log.d("messageDY : ", dy + "");
                scrollY += dy;
                if (scrollY > 100) {
                    //thirdTitleBar.setVisibility(View.GONE);
                } else {
                    //thirdTitleBar.setVisibility(View.VISIBLE);
                }
                //Log.d("message : ", scrollY + "");
            }
        });
        recyclerView.setLayoutManager(gridLayoutManager);
        Comingrecord comingrecord;
        try {
            comingrecord = (Comingrecord) cacheUtil.getAsObject(ConstantCode.PUPULAR_RECORD);
            if (comingrecord != null) {
                initListView(comingrecord,STROE);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        /**
         * 记录recyclerView 在视图的位置添加滚动事件
         */
        recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(@NonNull RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                if (recyclerView.getLayoutManager() != null) {
                    getPositionAndOffset();
                }
            }
        });
        //关闭下拉
        swipeRefresh.setEnableRefresh(false);
        //底部信息
        swipeRefresh.setRefreshFooter(new ClassicsFooter(CustomApplication.getContext()));
        swipeRefresh.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                RequestParams params = new RequestParams();
                params.put("city", "哈尔滨");
                params.put("start", start + "");
                params.put("count", "20");
                requestData(params);
                //requestData(null);
                swipeRefresh.finishLoadMore(2000);
            }
        });
        popularSearch.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getActivity(), SearchPageActivity.class);
                intent.putExtra("category", "");
                getActivity().startActivityForResult(intent, ConstantCode.requestCode);
            }
        });
        return view;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }

    private void requestData(RequestParams params) {
        RequestCenter.getRequest(HttpConstants.POPULAR, params, Comingrecord.class, new DisposeDataListener() {
            @Override
            public void onSuccess(Object responseObj) {
                Comingrecord comingrecord = (Comingrecord) responseObj;
                //缓存保存十分钟
                cacheUtil.put(ConstantCode.PUPULAR_RECORD, comingrecord);
                //填充数据
                initListView(responseObj,INTERNET);
            }

            @Override
            public void onFailure(Object reasonObj) {

            }
        });
    }

    /**
     * 让RecyclerView滚动到指定位置
     */
    private void scrollToPosition() {
        if (recyclerView.getLayoutManager() != null && lastPosition >= 0) {
            ((LinearLayoutManager) recyclerView.getLayoutManager()).scrollToPositionWithOffset(lastPosition, lastOffset);
        }
    }

    /**
     * 记录RecyclerView当前位置
     */
    private void getPositionAndOffset() {
        LinearLayoutManager layoutManager = (LinearLayoutManager) recyclerView.getLayoutManager();
        //获取可视的第一个view
        View topView = layoutManager.getChildAt(0);
        if (topView != null) {
            //获取与该view的顶部的偏移量
            lastOffset = topView.getTop();
            //得到该View的数组位置
            lastPosition = layoutManager.getPosition(topView);
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        // Log.d("1237", data.getIntExtra("name",10)+" ");
        // Bundle bundle=data.getExtras();
        // Log.d("1237",  bundle.getInt("name")+"");

    }

    private void initListView(Object responseObj,String from) {
        Comingrecord comingrecord = (Comingrecord) responseObj;
        if (responseObj != null && comingrecord.getCount() > 0) {
            if (start == 0) {
                adapter = new ComingAdapter(comingrecord.getSubjects());
            } else {
                adapter.add(comingrecord.getSubjects());
            }
            if(INTERNET.equals(from)){
                //从缓存中获取的数据不更新起始号
                start += comingrecord.getSubjects().size();
            }
            if (start == comingrecord.getTotal()) {
                swipeRefresh.setNoMoreData(true);
            }
            Banner banner = (Banner) LayoutInflater.from(getActivity()).inflate(R.layout.popular_header, recyclerView, false);
            //设置图片加载器
            banner.setImageLoader(new GlideImageLoader());
            List<String> images = new ArrayList<String>();
            images.add("https://static.sesine.com/wechat-weapp-movie" + "/images/banner_1.jpg");
            images.add("https://static.sesine.com/wechat-weapp-movie" + "/images/banner_2.jpg");
            images.add("https://static.sesine.com/wechat-weapp-movie" + "/images/banner_3.jpg");
            images.add("https://static.sesine.com/wechat-weapp-movie" + "/images/banner_4.jpg");
            images.add("https://static.sesine.com/wechat-weapp-movie" + "/images/banner_5.jpg");
            //设置图片集合
            banner.setImages(images);
            //banner设置方法全部调用完毕时最后调用
            banner.start();
            adapter.setHeaderView(banner);
                    /*View fbanner = (View) LayoutInflater.from(getActivity()).inflate(R.layout.popular_footer, recyclerView, false);
                    adapter.setFooterView(fbanner);*/
            adapter.setOnItemClickListener(new OnItemClickListener() {
                @Override
                public void onItemClick(View view, int position) {
                    SubjectsBean subjectsBean;
                    //recyclerView.getChildAdapterPosition(view);
                    if (adapter.getmHeaderView() != null) {
                        if (position == 0) {
                            ToastUtil.show("点击的是顶部");
                        } else {
                            if (adapter.getmFooterView() == null) {
                                position = position - 1;
                                subjectsBean = adapter.getSubjects().get(position);
                                Intent intent = new Intent(getActivity(), FilmDetailsActivity.class);
                                intent.putExtra("id", subjectsBean.getId());
                                getActivity().startActivityForResult(intent, ConstantCode.requestCode);
                            } else {

                            }
                        }
                    } else {

                    }
                }

                @Override
                public void onCategoryClick(View view, String category) {
                           /* Intent intent = new Intent(getActivity(), SearchResultActivity.class);
                            intent.putExtra("category", category);
                            getActivity().startActivityForResult(intent, ConstantCode.requestCode);*/
                }
            });
            recyclerView.setAdapter(adapter);
            scrollToPosition();
            swipeRefresh.setVisibility(View.VISIBLE);
            loadingView.setVisibility(View.GONE);
        }
    }

}
